﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Threading.Tasks;
using MasterDetailTemplate.Models;
using MasterDetailTemplate.Services;
using Xamarin.Forms;

namespace MasterDetailTemplate.Converters
{
    /// <summary>
    /// 时间转String
    /// </summary>
    public class DateToStringConventer : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter,
            CultureInfo culture)
        {
            long id = (long)value;
            var eventStorage = new EventStorage(new PreferenceStorage());

            var sourceTask = new TaskCompletionSource<Event>();
            var task1 = sourceTask.Task;
            Task.Run(async () => {
                var result = await eventStorage.GetEventAsync(id);
                sourceTask.SetResult(result);
            });

            var _event = task1.Result;


            // Event _event = new Event();
            if (_event.Attribute == 1)
            {
                //纪念日
                DateTime day = _event.Date;
                return day.ToString("yyyy-MM-dd");
            }
            else if (_event.Attribute == 2)
            {
                DateTime date = _event.Date;
                DateTime now = DateTime.Now;
                if (date.ToString("MM/dd/yyyy")
                    .Equals(now.ToString("MM/dd/yyyy")))
                {
                    return "今天";
                }

                TimeSpan span = date.Subtract(now);
                if (span.Days < 0)
                {
                    return "过了" + Math.Abs(span.Days) + "天";
                }
                else
                {
                    return (span.Days + 1) + "天后";
                }
            }

            return "";
        }

        public object ConvertBack(object value, Type targetType, object parameter,
            CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}
